<template>
	<view class="address-edit-container">
		<u-form :model="addressForm" ref="uForm" :error-type="['message']" label-width="160">
			<u-form-item label="收货人" prop="receiverName" required>
				<u-input v-model="addressForm.receiverName" placeholder="请输入收货人姓名" />
			</u-form-item>

			<u-form-item label="手机号码" prop="receiverPhone" required>
				<u-input v-model="addressForm.receiverPhone" placeholder="请输入手机号码" type="number" />
			</u-form-item>

			<u-form-item label="所在地区" prop="province" required @click="showRegionPicker">
				<view class="region-select">
					<text v-if="addressForm.province">{{addressForm.province}} {{addressForm.city}}
						{{addressForm.district}}</text>
					<text v-else class="placeholder">请选择所在地区</text>
					<u-icon name="arrow-right" size="20" color="#c0c4cc"></u-icon>
				</view>
			</u-form-item>

			<u-form-item label="详细地址" prop="detailAddress" required>
				<u-input v-model="addressForm.detailAddress" placeholder="请输入详细地址" type="textarea" />
			</u-form-item>

			<u-form-item label="设为默认地址">
				<u-switch v-model="addressForm.isDefault" active-value="1" inactive-value="0"></u-switch>
			</u-form-item>
		</u-form>

		<view class="submit-btn">
			<u-button type="primary" text="保存" @click="saveAddress"></u-button>
		</view>

		<!-- 自定义地区选择器 -->
		<u-popup mode="bottom" height="500" :show="showRegion" @close="cancelRegion">
			<view class="region-picker">
				<view class="region-picker-header">
					<text @click="cancelRegion">取消</text>
					<text>选择地区</text>
					<text @click="confirmRegion">确定</text>
				</view>
				<view class="region-picker-tabs">
					<view 
						class="tab-item" 
						:class="{ active: currentTab === 0 }" 
						@click="switchTab(0)"
					>
						<text>{{ tempProvince.name || '请选择' }}</text>
					</view>
					<view 
						class="tab-item" 
						:class="{ active: currentTab === 1, disabled: !tempProvince.name }" 
						@click="tempProvince.name && switchTab(1)"
					>
						<text>{{ tempCity.name || '请选择' }}</text>
					</view>
					<view 
						class="tab-item" 
						:class="{ active: currentTab === 2, disabled: !tempCity.name }" 
						@click="tempCity.name && switchTab(2)"
					>
						<text>{{ tempArea.name || '请选择' }}</text>
					</view>
				</view>
				<scroll-view scroll-y class="region-picker-content" :style="{ height: '350rpx' }">
					<view 
						class="region-item" 
						v-for="(item, index) in currentList" 
						:key="index"
						@click="selectRegion(item)"
						:class="{ active: isSelected(item) }"
					>
						<text>{{ item.name }}</text>
						<u-icon v-if="isSelected(item)" name="checkmark" color="#2979ff" size="30"></u-icon>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import { provinceList } from '@/constant/province.js'
	
	export default {
		data() {
			return {
				addressId: null, // 地址ID，编辑时有值
				addressForm: {
					receiverName: '',
					receiverPhone: '',
					province: '',
					city: '',
					district: '',
					detailAddress: '',
					isDefault: '0' // 使用字符串 '0' 和 '1' 而不是布尔值
				},
				showRegion: false, // 是否显示地区选择器
				currentTab: 0, // 当前选中的标签页，0-省，1-市，2-区
				provinceList: provinceList, // 省份列表
				cityList: [], // 城市列表
				areaList: [], // 区域列表
				selectedProvince: {}, // 选中的省份
				selectedCity: {}, // 选中的城市
				selectedArea: {}, // 选中的区域
				tempProvince: {}, // 临时选中的省份
				tempCity: {}, // 临时选中的城市
				tempArea: {}, // 临时选中的区域
				rules: {
					receiverName: [{
						required: true,
						message: '请输入收货人姓名',
						trigger: ['blur', 'change']
					}],
					receiverPhone: [{
							required: true,
							message: '请输入手机号码',
							trigger: ['blur', 'change']
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: '手机号码格式不正确',
							trigger: ['blur', 'change']
						}
					],
					province: [{
						required: true,
						message: '请选择所在地区',
						trigger: ['blur', 'change']
					}],
					detailAddress: [{
						required: true,
						message: '请输入详细地址',
						trigger: ['blur', 'change']
					}]
				}
			}
		},
		computed: {
			// 当前显示的列表
			currentList() {
				if (this.currentTab === 0) {
					return this.provinceList;
				} else if (this.currentTab === 1) {
					return this.cityList;
				} else {
					return this.areaList;
				}
			}
		},
		onReady() {
			// 在组件就绪后设置表单验证规则
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(options) {
			console.log('编辑地址页面参数:', options);
			
			// 如果有地址对象，则是编辑地址
			if (options.address) {
				try {
					const addressObj = JSON.parse(decodeURIComponent(options.address));
					console.log('解析的地址对象:', addressObj);
					
					// 设置地址ID
					this.addressId = addressObj.addressId;
					
					// 设置表单数据
					this.addressForm = {
						receiverName: addressObj.receiverName || '',
						receiverPhone: addressObj.receiverPhone || '',
						province: addressObj.province || '',
						city: addressObj.city || '',
						district: addressObj.district || '',
						detailAddress: addressObj.detailAddress || '',
						isDefault: addressObj.isDefault || '0'
					};
					
					// 设置已选择的省市区
					this.setSelectedRegion();
				} catch (e) {
					console.error('解析地址对象失败:', e);
				}
			} else if (options.id) {
				// 兼容旧的方式，通过ID获取地址详情
				this.addressId = options.id;
				this.getAddressDetail();
			}
		},
		methods: {
			// 设置已选择的省市区
			setSelectedRegion() {
				if (this.addressForm.province && this.addressForm.city && this.addressForm.district) {
					// 查找并设置省份
					const province = this.provinceList.find(p => p.name === this.addressForm.province);
					if (province) {
						this.selectedProvince = province;
						
						// 设置城市列表
						if (province.city) {
							this.cityList = province.city;
							
							// 查找并设置城市
							const city = province.city.find(c => c.name === this.addressForm.city);
							if (city) {
								this.selectedCity = city;
								
								// 设置区域列表
								if (city.area) {
									this.areaList = city.area;
									
									// 查找并设置区域
									const area = city.area.find(a => a.name === this.addressForm.district);
									if (area) {
										this.selectedArea = area;
									}
								}
							}
						}
					}
				}
			},
			
			// 获取地址详情
			getAddressDetail() {
				// 获取用户信息
				const userInfo = this.$user.getUserInfo();
				
				uni.showLoading({
					title: '加载中...'
				});
				
				this.$api.getAddressDetail({
					id: this.addressId,
					openid: userInfo.openid
				}).then(res => {
					uni.hideLoading();
					if (res) {
						// 将后端返回的数据映射到表单字段
						this.addressForm = {
							receiverName: res.receiverName || '',
							receiverPhone: res.receiverPhone || '',
							province: res.province || '',
							city: res.city || '',
							district: res.district || '',
							detailAddress: res.detailAddress || '',
							isDefault: res.isDefault || '0'
						};
						
						// 设置已选择的省市区
						this.setSelectedRegion();
					}
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
						title: '获取地址详情失败',
						icon: 'none'
					});
				});
			},
			
			// 显示地区选择器
			showRegionPicker() {
				// 初始化临时选择
				this.tempProvince = JSON.parse(JSON.stringify(this.selectedProvince || {}));
				this.tempCity = JSON.parse(JSON.stringify(this.selectedCity || {}));
				this.tempArea = JSON.parse(JSON.stringify(this.selectedArea || {}));
				
				// 设置当前标签页
				if (this.tempArea.name) {
					this.currentTab = 2;
				} else if (this.tempCity.name) {
					this.currentTab = 1;
				} else {
					this.currentTab = 0;
				}
				
				// 确保城市和区域列表已加载
				if (this.tempProvince.name && this.tempProvince.city) {
					this.cityList = this.tempProvince.city;
					
					if (this.tempCity.name && this.tempCity.area) {
						this.areaList = this.tempCity.area;
					}
				}
				
				this.showRegion = true;
			},
			
			// 切换标签页
			switchTab(index) {
				this.currentTab = index;
			},
			
			// 选择地区
			selectRegion(item) {
				if (this.currentTab === 0) {
					// 选择省份
					this.tempProvince = JSON.parse(JSON.stringify(item));
					this.tempCity = {};
					this.tempArea = {};
					
					// 更新城市列表
					this.cityList = item.city || [];
					this.areaList = [];
					
					// 自动切换到城市选择
					this.currentTab = 1;
				} else if (this.currentTab === 1) {
					// 选择城市
					this.tempCity = JSON.parse(JSON.stringify(item));
					this.tempArea = {};
					
					// 更新区域列表
					this.areaList = item.area || [];
					
					// 自动切换到区域选择
					this.currentTab = 2;
				} else {
					// 选择区域
					this.tempArea = JSON.parse(JSON.stringify(item));
				}
			},
			
			// 判断是否选中
			isSelected(item) {
				if (this.currentTab === 0) {
					return this.tempProvince.code === item.code;
				} else if (this.currentTab === 1) {
					return this.tempCity.code === item.code;
				} else {
					return this.tempArea.code === item.code;
				}
			},
			
			// 取消选择
			cancelRegion() {
				this.showRegion = false;
			},
			
			// 确认选择
			confirmRegion() {
				// 验证是否选择了省市区
				if (!this.tempProvince.name) {
					uni.showToast({
						title: '请选择省份',
						icon: 'none'
					});
					return;
				}
				
				if (!this.tempCity.name) {
					uni.showToast({
						title: '请选择城市',
						icon: 'none'
					});
					return;
				}
				
				if (!this.tempArea.name) {
					uni.showToast({
						title: '请选择区域',
						icon: 'none'
					});
					return;
				}
				
				// 更新选中的省市区
				this.selectedProvince = JSON.parse(JSON.stringify(this.tempProvince));
				this.selectedCity = JSON.parse(JSON.stringify(this.tempCity));
				this.selectedArea = JSON.parse(JSON.stringify(this.tempArea));
				
				// 更新表单数据
				this.addressForm.province = this.selectedProvince.name;
				this.addressForm.city = this.selectedCity.name;
				this.addressForm.district = this.selectedArea.name;
				
				this.showRegion = false;
			},
			
			// 保存地址
			saveAddress() {
				console.log('保存按钮被点击');
				
				// 先检查地区是否已选择
				if (!this.addressForm.province || !this.addressForm.city || !this.addressForm.district) {
					uni.showToast({
						title: '请选择所在地区',
						icon: 'none'
					});
					return;
				}
				
				// 手动验证表单
				this.$refs.uForm.validate().then(valid => {
					console.log('表单验证结果:', valid);
					
					if (valid) {
						// 获取用户信息
						const userInfo = this.$user.getUserInfo();
						console.log('用户信息:', userInfo);
						
						if (!userInfo || !userInfo.openid) {
							uni.showToast({
								title: '请先登录',
								icon: 'none'
							});
							return;
						}
						
						uni.showLoading({
							title: '保存中...'
						});
						
						// 构建请求参数
						const params = {
							...this.addressForm,
							openid: userInfo.openid,
							addressId: this.addressId
						};
						console.log('请求参数:', params);
						
						// 如果有地址ID，则是编辑地址
						if (this.addressId) {
							params.id = this.addressId;
							this.$api.updateAddress(params)
								.then(res => {
									console.log('更新地址成功:', res);
									uni.hideLoading();
									uni.showToast({
										title: '修改成功',
										icon: 'success'
									});
									setTimeout(() => {
										uni.navigateBack();
									}, 1500);
								})
								.catch(err => {
									console.error('更新地址失败:', err);
									uni.hideLoading();
									uni.showToast({
										title: '修改失败: ' + (typeof err === 'string' ? err : '请重试'),
										icon: 'none'
									});
								});
						} else {
							// 新增地址
							this.$api.addAddress(params)
								.then(res => {
									console.log('添加地址成功:', res);
									uni.hideLoading();
									uni.showToast({
										title: '添加成功',
										icon: 'success'
									});
									setTimeout(() => {
										uni.navigateBack();
									}, 1500);
								})
								.catch(err => {
									console.error('添加地址失败:', err);
									uni.hideLoading();
									uni.showToast({
										title: '添加失败: ' + (typeof err === 'string' ? err : '请重试'),
										icon: 'none'
									});
								});
						}
					} else {
						console.log('表单验证失败');
					}
				}).catch(errors => {
					console.error('表单验证错误:', errors);
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.address-edit-container {
		min-height: calc(100vh - 80rpx);
		background-color: #ffffff;
		padding: 40rpx;

		.region-select {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 70rpx;

			.placeholder {
				color: #c0c4cc;
			}
		}

		.submit-btn {
			margin-top: 60rpx;
		}
		
		.region-picker {
			background-color: #ffffff;
			
			.region-picker-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 90rpx;
				padding: 0 30rpx;
				border-bottom: 1rpx solid #f2f2f2;
				
				text {
					font-size: 28rpx;
					
					&:first-child {
						color: #909399;
					}
					
					&:last-child {
						color: #2979ff;
					}
				}
			}
			
			.region-picker-tabs {
				display: flex;
				height: 80rpx;
				border-bottom: 1rpx solid #f2f2f2;
				
				.tab-item {
					flex: 1;
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 28rpx;
					color: #606266;
					position: relative;
					
					&.active {
						color: #2979ff;
						
						&::after {
							content: '';
							position: absolute;
							bottom: 0;
							left: 50%;
							transform: translateX(-50%);
							width: 120rpx;
							height: 4rpx;
							background-color: #2979ff;
						}
					}
					
					&.disabled {
						color: #c0c4cc;
					}
				}
			}
			
			.region-picker-content {
				.region-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					height: 90rpx;
					padding: 0 30rpx;
					font-size: 28rpx;
					color: #303133;
					
					&.active {
						color: #2979ff;
					}
				}
			}
		}
	}
</style>